﻿using FileExplorerTree;
using Antivirus.Domain.Logic.Scanners;

namespace UIFileExplorerProgress
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Antivirus.Domain.DataLayer.Repositories;
    using Antivirus.Domain.Logic.Hashers;

    public class DefaultPresenter : IPresenter
    {
        private readonly Queue<string> _targetsQueue = new Queue<string>();
        private readonly FileExplorer _fileExplorer = new FileExplorer();
        private readonly DefaultScanner _scanner;
        private readonly IExplorerProgressView _view;

        public DefaultPresenter(IExplorerProgressView view)
        {
            var repository = new XmlFileVirusSignatureRepository("VirusDatabase.xml");
            var virusSignatures = repository.GetAllVirusSignatures();

            _scanner = new DefaultScanner(new Md5Hasher(), virusSignatures);
            _view = view;

            _scanner.FileScanCompleted += OnFileScanCompleted;
            _scanner.BatchScanCompleted += OnBatchScanCompleted;
        }

        public void StartScan(IEnumerable<string> targets)
        {
            _view.ClearInfectedFiles();
            _view.ResetProgressBar();

            if (!targets.Any())
                return;            

            _targetsQueue.Clear();
            foreach (var target in targets)
                _targetsQueue.Enqueue(target);

            StartScanInternal();
        }

        public void StopScan()
        {
            _view.ResetProgressBar();
            _scanner.Stop();
        }

        public FileExplorer FileExplorer
        {
            get { return _fileExplorer; }
        }

        private void StartScanInternal()
        {
            if (_targetsQueue.Count == 0)
                return;

            var target = _targetsQueue.Dequeue();

            if (File.Exists(target))
            {
                _scanner.ScanFile(target);
            }
            else if (Directory.Exists(target))
            {
                _scanner.ScanDirectory(target, true);
            }
        }

        private void OnFileScanCompleted(object sender, FileScanCompletedEventArgs args)
        {
            if (!_view.ProgressBarInitialized)
                _view.InitializeProgressBar(args.TotalFilesCount);

            _view.ProgressBarStep();

            if (args.IsVirus)
                _view.AddInfectedFile(args.Filename, args.VirusSignature.Name);
        }

        public void OnBatchScanCompleted(object sender, BatchScanCompletedEventArgs args)
        {
            StartScanInternal();
        }
    }
}
